package com.ruoyi.quartz.task.wheather;


import com.ruoyi.yanjing.domain.Weather;
import com.ruoyi.yanjing.gaode.GaoDeApi;
import com.ruoyi.yanjing.gaode.constant.WeatherConstant;
import com.ruoyi.yanjing.gaode.model.GaoDeResult;
import com.ruoyi.yanjing.gaode.model.Live;
import com.ruoyi.yanjing.service.IWeatherForecastService;
import com.ruoyi.yanjing.service.IWeatherService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component("autoPullGaoDeWeatherJob")
public class AutoPullGaoDeWeatherJob  implements Runnable {

    private static final Log log = LogFactory.getLog(AutoPullGaoDeWeatherJob.class);


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IWeatherService weatherService;



    /**
     * 北京市
     * 城市编码表：doc/AMap_adcode_citycode.xlsx
     */
    private static final String AD_CODE = "110000";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run() {
        log.info("Pull live weather data begin==================>");
        long startTime = System.currentTimeMillis();

        // 拉取实时天气
        this.saveLive(AD_CODE);

        long endTime = System.currentTimeMillis();
        log.info("spend time:" + (endTime - startTime));
        log.info("Pull live weather data end<==================");
    }

    /**
     * 实时天气
     *
     * @param adcode
     */
    private void saveLive(String adcode) {
        StringBuilder sendUrl = new StringBuilder(WeatherConstant.WEATHER_URL)
                .append("?key=").append(GaoDeApi.KEY_VALUE)
                .append("&city=").append(adcode)
                .append("&extensions=base");
        ResponseEntity<GaoDeResult> responseEntity = restTemplate.getForEntity(sendUrl.toString(), GaoDeResult.class);
        // 请求异常，可能由于网络等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Gaode interface error");
            return;
        }

        // 请求失败
        GaoDeResult gaoDeResult = responseEntity.getBody();
        String status = gaoDeResult.getStatus();
        if (!status.equals(GaoDeApi.SUCCESS)) {
            log.info("Request for Gaode interface failed");
            return;
        }

        List<Live> lives = gaoDeResult.getLives();
        if (CollectionUtils.isEmpty(lives)) {
            return;
        }

        // 实况天气
        Live live = lives.get(0);
        Weather weather = new Weather();
        weather.setProvince(live.getProvince());
        weather.setCity(live.getCity());
        weather.setAdcode(live.getAdcode());
        weather.setWeather(live.getWeather());
//        weather.setWeatherImg(WeatherType.getCodeByDes(live.getWeather()));
        weather.setTemperature(live.getTemperature());
        weather.setWinddirection(live.getWinddirection());
        weather.setWindpower(live.getWindpower());
        weather.setHumidity(live.getHumidity());
        weather.setReporttime(live.getReporttime());
        weatherService.insertWeather(weather);
    }
}
